//
//  XLTabBarController.m
//  XLTabBarController
//
//  Created by ZxlAndZyp on 2019/1/8.
//  Copyright © 2019 zuoxueliang. All rights reserved.
//

#import "XLTabBarController.h"

@interface XLTabBarController ()<XLTabBarDelegate>

@end

@implementation XLTabBarController

- (instancetype)initWithTabBarControllers:(NSArray *)controllers norImages:(NSArray *)norImages selImages:(NSArray *)selImages titles:(NSArray *)titles config:(XLTabBarConfig *)config
{
    if (self = [super init]) {
        self.viewControllers = controllers;
        self.xlTabBar = [[XLTabBar alloc] initWithFrame:self.tabBar.frame norImages:norImages selImages:selImages titles:titles config:config];
        [self setValue:self.xlTabBar forKey:@"tabBar"];
        self.xlTabBar.tabBarDelegate = self;
        [XLTabBarConfig tabBarConfig].tabBarController = self;
        // KVO
        [self addObserver:self
               forKeyPath:@"selectedIndex"
                  options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew
                  context:nil];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    NSInteger selectedIndex = [change[@"new"] integerValue];
    self.xlTabBar.selectedIndex = selectedIndex;
}

- (void)tabBar:(XLTabBar *)tabBar disSelectIndex:(NSInteger)selectIndex
{
    self.selectedIndex = selectIndex;
}

- (void)dealloc {
    NSLog(@"被销毁了");
    [self removeObserver:self forKeyPath:@"selectedIndex"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
